<template>
    <el-form label-width="100px">
        <el-form-item label="spu名称">
            {{spu.spuName}}
        </el-form-item>
        <el-form-item label="sku名称">
            <el-input placeholder="sku名称" v-model="skuForm.skuName" ></el-input>
        </el-form-item>
        <el-form-item label="价格">
            <el-input placeholder="sku名称" type="number" v-model="skuForm.price"></el-input>
        </el-form-item>
        <el-form-item label="重量">
            <el-input placeholder="重量" type="number" v-model="skuForm.weight"></el-input>
        </el-form-item>
        <el-form-item label="规则描述">
            <el-input placeholder="规则描述" type="textarea" rows="4" v-model="skuForm.skuDesc"></el-input>
        </el-form-item>

        <el-form-item label="平台属性">
            <el-form :inline="true" label-width="100px">
                <el-form-item :label="attr.attrName" v-for="(attr,index) in attrList" :key="attr.id">
                    <el-select v-model="attr.attrIdValueId">
                        <el-option  :value="`${attr.id}:${attrValue.id}`" :label="attrValue.valueName" v-for="(attrValue,index) in attr.attrValueList" :key="attrValue.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </el-form-item>

        <el-form-item label="销售属性">
            <el-form :inline="true" label-width="100px" >
                <el-form-item :label="saleAttr.saleAttrName" v-for="(saleAttr,index) in spuSaleAttrList" :key="saleAttr.id">
                    <el-select v-model="saleAttr.saleAttrIdValueId">
                        <el-option :value="`${saleAttr.id}:${saleAttrValue.id}`" :label="saleAttrValue.saleAttrValueName" v-for="(saleAttrValue,index) in saleAttr.spuSaleAttrValueList" :key="saleAttrValue.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
        </el-form-item>

        <el-form-item label="图片列表" >
            <el-table border stripe :data="spuImageList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="图片" >
                    <template v-slot="{row}">
                        <img :src="row.imgUrl" alt="" style="width: 100px;height: 80px;">
                    </template>
                </el-table-column>
                <el-table-column label="名称" prop="imgName"></el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{row}">
                        <el-button @click="setDefault(row,spuImageList)" v-if="row.isDefault === '0'" type="primary" size="small">设为默认</el-button>
                        <el-tag v-else type="danger">默认</el-tag>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="save">保存</el-button>
            <el-button @click="emits('changeState',1)">取消</el-button>
        </el-form-item>
    </el-form>
    

</template>

<script lang="ts">
    import { defineComponent } from 'vue';

    export default defineComponent({
        name:'SkuForm'
    })
</script>

<script setup lang="ts">
import type { SpuData, SpuImageData, SpuSaleAttrData } from '@/api/spu'
import {onMounted,ref} from 'vue'
import attrApi, { type AttrData } from '@/api/attr'
import skuApi, { type SkuAttrValueData, type SkuData, type SkuImageData, type SkuSaleAttrValueData } from '@/api/sku';
import { useCategoryStore } from '@/stores/category';
import { storeToRefs } from 'pinia';
import { ElMessage } from 'element-plus';


const props = defineProps<{
    spu:SpuData
}>()

const emits = defineEmits(['changeState'])




// 获取初始化展示数据
const attrList = ref<AttrData[]>([])
const spuImageList = ref<SpuImageData[]>([])
const spuSaleAttrList = ref<SpuSaleAttrData[]>([])

const categoryStore = useCategoryStore()
const {category1Id,category2Id,category3Id} = storeToRefs(categoryStore)

const getInitAddSkuFormData = async () => {
  // http://localhost:3000/app-dev/admin/product/attrInfoList/2/13/61
  const promise1 = attrApi.getList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number
  )
  // http://localhost:3000/app-dev/admin/product/spuImageList/6
  const promise2 = skuApi.getSpuImageList(props.spu.id as number)
  // http://localhost:3000/app-dev/admin/product/spuSaleAttrList/6
  const promise3 = skuApi.getSpuSaleAttrList(props.spu.id as number)

  try {
    const result = await Promise.all([promise1,promise2,promise3])
    attrList.value = result[0]
    let imgList = result[1]
    imgList.forEach(item => item.isDefault = '0')
    spuImageList.value = imgList
    spuSaleAttrList.value = result[2]
  } catch (error) {
    ElMessage.error('获取添加sku的初始化动态数据失败')
  } 
}

onMounted(() => {
  getInitAddSkuFormData()
})


// 收集数据
// 收集什么 收集到哪
const skuForm = ref<SkuData>({
  // v-model直接收集
  price: 0,
  skuName: '',
  skuDesc: '',
  weight: '',

  // 父组件或者仓库可以得到
  spuId: 0,
  tmId: 0,
  category3Id: 0,

  // 需要自己写代码去收集
  skuDefaultImg: '',
  skuImageList: [],
  skuAttrValueList: [],
  skuSaleAttrValueList: []
})

const skuImageList = ref<SkuImageData[]>([]) //专门用来收集sku自己的图片列表

// 收集sku图片列表
const handleSelectionChange = (val:any) => {
  // console.log(val);
  skuImageList.value = val 
}


// 排他操作设置默认图片
const setDefault = (row:SpuImageData,spuImageList:SpuImageData[]) => {
  // 先让所有的图片都为0
  spuImageList.forEach(item => item.isDefault = '0')
  // 再让点击选中的图片为1
  row.isDefault = '1'
  
  // 收集sku的默认图片路径
  skuForm.value.skuDefaultImg = row.imgUrl
}
// 保存操作

const save = async () => {
    let sku = skuForm.value
    // 把sku当中从父组件和仓库拿到的数据整理到位
    sku.category3Id = category3Id.value as number
    sku.spuId = props.spu.id as number 
    sku.tmId = props.spu.tmId as number
     // 整理sku的图片列表
    sku.skuImageList = skuImageList.value.map(item => {
        return {
            imgName:item.imgName,
            imgUrl:item.imgUrl,
            spuImgId:item.id as number,
            isDefault:item.isDefault
        }
    })
    // 整理sku的平台属性值列表
    sku.skuAttrValueList = attrList.value.reduce((prev,item) => {
        if(item.attrIdValueId){
            let [attrId,valueId] = item.attrIdValueId.split(':')
            let obj = {attrId,valueId}
            prev.push(obj)
        }
        return prev
    },[] as SkuAttrValueData[])  // 将收集到的信息解构添加到数组中

    // 整理sku的销售属性值列表
    sku.skuSaleAttrValueList = spuSaleAttrList.value.reduce((prev,item) => {
        if(item.saleAttrIdValueId){
            let [saleAttrId,saleAttrValueId] = item.saleAttrIdValueId.split(':')
            let obj = {saleAttrId,saleAttrValueId}
            prev.push(obj)
        }
        return prev
    },[] as SkuSaleAttrValueData[])

    try {
        await skuApi.saveSkuInfo(sku)
        ElMessage.success('添加sku成功')
        emits('changeState',1)
    } catch (error) {
        ElMessage.error('添加sku失败')
    }

}

</script>

<style lang="less" scoped>

</style>